package com.cctc.security.support;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cctc.security.domain.User;
import com.cctc.security.services.UserService;

/*项目实现的用户查询服务,将用户信息查询出来*/
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

	@Autowired
	private UserService<User> userService;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		//取得用户的权限
		auths = userService.loadUserAuthoritiesByName(userName);

		User user = userService.getUserByName(userName);
		if (null == user) {
			throw new UsernameNotFoundException(userName);
		}

		User u = new User(user.getAccount(), user.getPassword(), user.getEnabled(), user.getAccountNonExpired(),
				user.getCredentialsNonExpired(), user.getAccountNonLocked(),auths);
		return u;
	}

}
